package com.store.orm.mysql.datasource;

import com.store.orm.config.MySQLConfig;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 连接池获取数据
 *
 * @author 宫静雨
 * @version 1.0
 */
public class PooledConnection {

    private Integer max = 50;
    private MySQLConfig config;
    private List<Connection> activePool = new ArrayList<>();
    private List<Connection> idlePool = new ArrayList<>();

    public PooledConnection(MySQLConfig config) {
        this.config = config;
        Integer init = 10;
        if (Objects.nonNull(config.getPool())) {
            this.max = config.getPool().getMax();
            init = config.getPool().getInit();
        }
        for (int i = 0; i < init; i++) {
            idlePool.add(init());
        }
    }

    public synchronized Connection get() {
        Connection client = null;
        int lastIndex = idlePool.size() - 1;
        if (lastIndex >= 0) {
            client = idlePool.remove(lastIndex);
            activePool.add(client);
        } else if (activePool.size() < this.max) {
            client = init();
            activePool.add(client);
        }
        return client;
    }

    public synchronized void close(Connection client) {
        if (idlePool.size() + activePool.size() >= this.max) {
            try {
                client.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else {
            idlePool.add(client);
            activePool.remove(client);
        }
    }

    private Connection init() {
        try {
            Class.forName(config.getDriver());
            return DriverManager.getConnection(config.getUrl(), config.getUsername(), config.getPassword());
        } catch (Exception e) {
            return null;
        }
    }
}